package service

import (
	"context"
	"encoding/json"
	"mini-app/config"
	"mini-app/config/redis"
	"mini-app/internal/define"
	"mini-app/internal/pkg"
	"net/url"
	"time"
	// "192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/logx"
	// "log"
)

type Auth struct{}

type WanxiangToken struct {
	AccessToken  string `json:"access_token"`  // 访问令牌
	TokenType    string `json:"token_type"`    // 令牌类型
	RefreshToken string `json:"refresh_token"` // 刷新令牌
	ExpiresIn    int    `json:"expires_in"`    // 访问令牌过期时间【秒】默认2小时
	Scope        string `json:"scope"`         // 作用范围
	SessionKey   string `json:"session_key"`   // 签名秘钥
	NewRegister  bool   `json:"new_register"`  // 是否新注册会员，令牌有效期内固定返回
}

// 万象回调，请求获取授权令牌
func (Auth) OauthCallback(ctx context.Context, token, code string, webServerRedirectUri string) (err error) {
	BaseURL := config.Config.WanxiangPoints.AuthURL
	
	logx.Info(context.Background(), "OauthCallback", logx.Any("token", token))
	logx.Info(context.Background(), "OauthCallback", logx.Any("code", code))
	logx.Info(context.Background(), "OauthCallback", logx.Any("webServerRedirectUri", webServerRedirectUri))
	logx.Info(context.Background(), "OauthCallback", logx.Any("BaseURL", BaseURL))

	var URL url.URL
	query := URL.Query()
	query.Add("scope", "read")
	query.Add("grant_type", "authorization_code")
	query.Add("mall_code", "2XRY00201")

	logx.Info(context.Background(), "OauthCallback", logx.Any("mall_code", "2XRY00201"))
	params := url.Values{}
	// 客户端应用ID
	params.Add("client_id", config.Config.WanxiangPoints.AppID)
	// 客户端应用秘钥
	params.Add("client_secret", config.Config.WanxiangPoints.APPSecret)
	// 前端传入的code
	params.Add("code", code)
	// 客户端重定向接收code的地址【一点万象平台上配置的"微信小程序重定向地址"】
	params.Add("redirect_uri", webServerRedirectUri)
	
	logx.Info(context.Background(), "OauthCallback", logx.Any("client_id",  config.Config.WanxiangPoints.AppID))
	logx.Info(context.Background(), "OauthCallback", logx.Any("client_secret",  config.Config.WanxiangPoints.APPSecret))
	logx.Info(context.Background(), "OauthCallback", logx.Any("post",  BaseURL+"?"+query.Encode()))
	logx.Info(context.Background(), "OauthCallback", logx.Any("redirect_uri",  webServerRedirectUri))

	rspBytes, rspErr := pkg.PostFormURLEncoded(BaseURL+"?"+query.Encode(), params)
	
	logx.Info(context.Background(), "OauthCallback", logx.Any("rspBytes",  rspBytes))
	if rspErr != nil {
		err = rspErr
		return
	}
	var response WanxiangToken
	err = json.Unmarshal(rspBytes, &response)
	if err != nil {
		return
	}
	// 保存accessToken【accessToken是用户级的】
	rdb := redis.NewDB()
	expireTime := time.Duration(response.ExpiresIn) * time.Second
	openid, _ := rdb.Get(ctx, define.MiniAppSessionOpenid+token).Result()
	rdb.Set(ctx, define.WanxiangPointsAccessToken+openid, response.AccessToken, expireTime)
	rdb.Set(ctx, define.WanxiangPointsSessionKey+openid, response.SessionKey, expireTime)

	logx.Info(context.Background(), "OauthCallback", logx.Any("response", openid + " : " + response.AccessToken + ":" + response.SessionKey))

	return
}
